from django import template
register = template.Library()
import urlparse
from django.conf import settings
import os

def _absolute_url(url):
    if url.startswith('http://') or url.startswith('https://'):
        return url
    domain = Site.objects.get_current().domain
    return 'http://%s%s' % (domain, url)

@register.simple_tag
def static(filename, flags=''):
    '''
    Required settings:
      STATIC_DOC_ROOT
      STATIC_DOC_ROOT_URL
    Usage:
      {% load static_tags %}
    
      {% static "css/print.css" %}
      {% static "css/print.css" no-timestamp %}
      {% static "i/spaver.gif" %}
    '''
    flags = set(f.strip() for f in flags.split(','))
    url = urlparse.urljoin(settings.STATIC_DOC_URL, filename)
    if 'absolute' in flags:
        url = _absolute_url(url)
    if (filename.endswith('.css') or filename.endswith('.js')) and 'no-timestamp' not in flags or \
       'timestamp' in flags:
        fullname = os.path.join(settings.STATIC_DOC_ROOT, filename)
        if os.path.exists(fullname):
            url += '?%d' % os.path.getmtime(fullname)
    return url
